<template>
  <div class="user-advertisement">
    <div class="mb-5 flex">
      <common-link path="/advertise"
        class="border border-purple-1300 bg-purple-1300 px-3 py-2.5 text-sm text-white rounded hover:bg-purple-1400 hover:border-purple-1400">
        {{$t('user_buyMoreAdvertisement')}}
      </common-link>
    </div>
    <div class="tTable"
      v-if="!isFirstLoad"
      style="overflow-x: auto;"
      v-loading="loading && !isFirstLoad">
      <table style="width: 100%; min-width: 780px;"
        v-if="tableData && tableData.length>0">
        <thead>
          <tr>
            <th style="width: 5%">
              <div class="cell">
                #
              </div>
            </th>
            <th style="width: 15%">
              <div class="cell">
                {{$t('user_id')}}
              </div>
            </th>
            <th style="width: 26%">
              <div class="cell text-left">
                {{$t('user_name')}}
              </div>
            </th>
            <th style="width: 16%">
              <div class="cell">
                {{$t('user_balances')}}
              </div>
            </th>
            <th style="width: 38%">
              <div class="cell text-right">
                {{$t('user_adStatus')}}
              </div>
            </th>
          </tr>
        </thead>
        <tbody>
          <tr class="el-table__row"
            v-for="(row, key) in tableData"
            :key="key">
            <td>
              <div class="cell">
                <p class="text-base text-gray-1000 break-words">
                  {{key+1}}
                </p>
              </div>
            </td>
            <td>
              <div class="cell">
                <p class="text-base text-gray-1000 break-words"
                  v-if="hasRealVal(row.id)">
                  {{ row.id }}
                </p>
              </div>
            </td>
            <td>
              <div class="cell text-left space-y-1">
                <p class="text-base font-semibold text-gray-1000 break-words"
                  v-if="row.tool && $websiteName(row.tool)">
                  {{$websiteName(row.tool)}}
                </p>
                <div v-if="row.tool && $websiteName(row.tool) && row.tool.handle">
                  <common-link path="/tool/:handle"
                    :params="{ handle:row.tool.handle }"
                    class="text-sm text-gray-1000 break-words hover:text-purple-1300 go-tool"
                    target="_blank">
                    {{ `https://www.toolify.ai${locale === 'en' ? '' : `/${locale}`}/tool/${row.tool.handle}`}}
                  </common-link>
                </div>
              </div>
            </td>
            <td>
              <div class="cell space-y-1">
                <p class="text-base font-semibold text-gray-1000 break-words"
                  v-if="hasRealVal(row.balance)">
                  $ {{row.balance}}
                </p>
                <p class="text-sm text-gray-1000"
                  v-if="hasRealVal(row.remaining_quota)">{{$t('user_numClicks', {num: row.remaining_quota})}}</p>
              </div>
            </td>
            <td>
              <template v-if="hasRealVal(row.remaining_quota) && row.remaining_quota > 0">
                <div class="cell flex items-center justify-end gap-x-7 gap-y-3 flex-wrap"
                  v-if="hasRealVal(row.status) && row.status === 1">
                  <div class="flex items-center gap-1">
                    <svg-icon className="w-3.5 h-3.5 text-sm"
                      :isDiv="true"
                      iconName='runing'></svg-icon>
                    <span class="text-base text-gray-1000">{{$t('user_running')}}</span>
                  </div>

                  <div class="flex items-center justify-center gap-1.5 px-3 py-1 bg-red-1000 rounded border border-red-1000 text-white hover:opacity-90 cursor-pointer"
                    @click="changeAdStstus(row,2)">
                    <svg-icon className="w-3.5 h-3.5 text-sm"
                      :isDiv="true"
                      iconName='stop_2'
                      v-if="!statusId || statusId !== row.id"></svg-icon>
                    <img :src="loadingSrc"
                      class="loading w-3.5 h-3.5"
                      alt=""
                      srcset=""
                      v-if="statusId === row.id">
                    <span class="whitespace-nowrap">{{$t('user_stopAd')}}</span>
                  </div>
                </div>
                <div class="cell flex items-center justify-end gap-x-7 gap-y-3 flex-wrap"
                  v-if="hasRealVal(row.status) && row.status === 2">
                  <div class="flex items-center gap-1">
                    <svg-icon className="w-3.5 h-3.5 text-sm"
                      :isDiv="true"
                      iconName='stop'></svg-icon>
                    <span class="text-base text-gray-1000">{{$t('user_stop')}}</span>
                  </div>

                  <div class="flex items-center justify-center gap-1.5 px-3 py-1 rounded border bg-purple-1300 border-purple-1300 text-white hover:opacity-90 cursor-pointer"
                    @click="changeAdStstus(row,1)">
                    <img :src="loadingSrc"
                      class="loading w-3.5 h-3.5"
                      alt=""
                      srcset=""
                      v-if="statusId === row.id">
                    <span class="whitespace-nowrap">{{$t('user_startAd')}}</span>
                  </div>
                </div>
              </template>
              <div class="cell flex items-center justify-end gap-x-7 gap-y-3 flex-wrap"
                v-else>
                <div class="flex items-center gap-1">
                  <svg-icon className="w-3.5 h-3.5 text-sm"
                    :isDiv="true"
                    iconName='noenough'></svg-icon>
                  <span class="text-base text-gray-1000">{{$t('user_noEnoughBalances')}}</span>
                </div>

                <common-link path="/advertise"
                  class="flex items-center justify-center gap-1.5 px-3 py-1 rounded border text-purple-1300 border-purple-1300 hover:bg-purple-1000 hover:border-purple-1000 cursor-pointer">
                  <span class="whitespace-nowrap">{{$t('user_buyMoreAdvertisement')}}</span>
                </common-link>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
      <el-empty v-else
        class="sm:flex-1"
        :description="$t('user_noData')"></el-empty>
    </div>

    <div class="tTable skeleton"
      v-else
      style="overflow-x: auto;">
      <el-skeleton animated>
        <template slot="template">
          <table style="width: 100%; min-width: 780px;">
            <thead>
              <tr>
                <th style="width: 5%">
                  <div class="cell">
                    <el-skeleton-item variant="div" />
                  </div>
                </th>
                <th style="width: 15%">
                  <div class="cell">
                    <el-skeleton-item variant="div" />
                  </div>
                </th>
                <th style="width: 26%">
                  <div class="cell">
                    <el-skeleton-item variant="div" />
                  </div>
                </th>
                <th style="width: 16%">
                  <div class="cell">
                    <el-skeleton-item variant="div" />
                  </div>
                </th>
                <th style="width: 38%">
                  <div class="cell">
                    <el-skeleton-item variant="div" />
                  </div>
                </th>
              </tr>
            </thead>
            <tbody>
              <tr class="el-table__row"
                v-for="(row, key) in 5"
                :key="key">
                <td v-for="(row, key) in 5"
                  :key="`td-${key}`">
                  <div class="cell">
                    <el-skeleton-item variant="div" />
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </template>
      </el-skeleton>
    </div>
    <div class="pagination"
      v-if="pagination.total && pagination.total > pagination.pageSize">
      <el-pagination :current-page="pagination.current"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.pageSize"
        :layout="_isMobile() ? minLayout : layout"
        :small="_isMobile() ? true : false"
        :total="pagination.total"
        :disabled="loading"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  name: 'UserAdvertisement',
  props: {},
  data() {
    return {
      loading: false,
      isFirstLoad: true,
      tableData: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
      },
      layout: 'total, sizes, prev, pager, next, jumper',
      minLayout: 'prev, next',

      statusId: null,
      loadingSrc: require('@/static/images/loading-white.png'),
    }
  },
  computed: {
    ...mapState({
      locale: (state) => state.locale,
    }),
  },
  created() {
    this.getList({
      per_page: 10,
      page: 1,
    })
  },
  methods: {
    async getList(page) {
      let req = JSON.parse(JSON.stringify({ ...page }))
      try {
        for (let item in req) {
          if (req[item] === null || req[item] === '') {
            delete req[item]
          }
        }

        const res = await this.$axiosApi.advertiseList(req)

        this.loading = false
        this.isFirstLoad = false
        if (res && res.code === 200) {
          this.tableData = res.data.data
          this.pagination.current = res.data.current_page
          this.pagination.total = res.data.total
          this.pagination.pageSize = res.data.per_page
        }
      } catch (error) {
        this.isFirstLoad = false
        this.loading = false
      }
    },
    async handleSizeChange(val) {
      if (this.loading) {
        return false
      }
      this.loading = true
      await this.getList({
        per_page: val,
        page: 1,
      })
      this.loading = false
      this.intoView()
    },
    async handleCurrentChange(val) {
      if (this.loading) {
        return false
      }
      this.loading = true
      await this.getList({
        per_page: this.pagination.pageSize,
        page: val,
      })
      this.loading = false
      this.intoView()
    },
    _isMobile() {
      if (process.browser) {
        let flag = navigator.userAgent.match(
          /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
        )
        return flag
      } else {
        return false
      }
    },

    fI18n(arg) {
      const hasKey = this.$i18n.t(arg)
      if (hasKey) {
        const result = this.$i18n.t(arg)
        return result
      }
      return arg
    },
    async changeAdStstus(row, status) {
      this.statusId = row.id
      try {
        const res = await this.$axiosApi.advertiseStatus(
          {
            status: status,
          },
          row.id
        )
        if (res && res.code === 200) {
          this.$message.success(
            this.$i18n.t(
              status === 1 ? 'user_startAdSuccess' : 'user_stopAdSuccess'
            )
          )
          row.status = status
        }
        this.statusId = null
      } catch (error) {
        this.statusId = null
      }
    },
    intoView() {
      const dom = document.querySelector('.tabs-box')
      if (dom) {
        const top = dom.offsetTop

        const targetScrollPosition = Math.max(top - 100, 0)

        let timer = setTimeout(() => {
          window.scrollTo({
            top: targetScrollPosition,
            behavior: 'auto',
          })

          this.$nextTick(() => {
            clearTimeout(timer)
          })
        })
      }
    },
  },
}
</script>
<style lang="scss" scoped>
@import '@/assets/css/common-table.scss';
.user-advertisement {
  .pagination {
    text-align: right;
    margin-top: 20px;
    ::v-deep .el-pagination {
      padding: 0;
      .el-pagination__jump {
        .el-input {
          margin-right: 0;
        }
      }
    }
  }
}
</style>